package com.atguigu.gulimall.search.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.ElasticSearchConfig;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class ProductSaveService {

    @Qualifier("esRestClient")
    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 商品上架功能，将商品相关的数据保存到ES中
     *
     * @param skuEsModelList
     */
    public void productUp(List<SkuEsModel> skuEsModelList) {

        // 1、建立一个索引，已经通过kibana创建了一个[ product ]索引


        // 2、保存数据到es中
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModelList) {
            // 指定索引
            IndexRequest indexRequest = new IndexRequest("product");
            // _id
            indexRequest.id(String.valueOf(skuEsModel.getSkuId()));
            
            indexRequest.source(JSONObject.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = null;
        try {
            bulkResponse = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("商品数据保存es失败", e);
        }
        if (bulkResponse != null) {
            System.out.println(Arrays.toString(bulkResponse.getItems()));
        }
    }
}
